#===istalismanplugin===
# -*- coding: utf-8 -*-

#  Talisman plugin
#  ping_plugin.py

#  Initial Copyright © 2007 dimichxp <dimichxp@gmail.com>
#  Modifications Copyright © 2007 Als <Als@exploit.in>

#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

ping_pending=[]
def handler_ping(type, source, parameters):
	nick=parameters
	groupchat=source[1]
	iq = xmpp.Iq('get')
	id = 'p'+str(random.randrange(1, 1000))
	globals()['ping_pending'].append(id)
	iq.setID(id)
	iq.addChild('query', {}, [], 'jabber:iq:version');
	if parameters:
		if GROUPCHATS.has_key(source[1]):
			nicks = GROUPCHATS[source[1]].keys()
			param = parameters.strip()
			if not nick in nicks:
				iq.setTo(param)
			else:
				if GROUPCHATS[groupchat][nick]['ishere']==0:
					reply(type, source, u'is he even here? :-O')
					return
				param=nick
				jid=groupchat+'/'+nick
				iq.setTo(jid)
	else:
		jid=groupchat+'/'+source[2]
		iq.setTo(jid)
		param=''
	t0 = time.time()
	JCON.SendAndCallForResponse(iq, handler_ping_answ,{'t0': t0, 'mtype': type, 'source': source, 'param': param})
	return


PINGBASE = {}

def handler_ping_log(jid, sec):
        dt = time.strftime('%d') +'.'+ time.strftime('%m') +'.'+ time.strftime('%Y')+' / '+time.strftime('%H') +':'+ time.strftime('%M') +':'+ time.strftime('%S')
        if not PINGBASE.has_key(jid):
                PINGBASE[jid] = {'pings':{}, 'min':sec, 'min_date':dt, 'max':sec, 'max_date':dt, 'average':0}
        if PINGBASE[jid]['min'] > sec:
                PINGBASE[jid]['min'] = sec
                PINGBASE[jid]['min_date'] = dt
        if PINGBASE[jid]['max'] < sec:
                PINGBASE[jid]['max'] = sec
                PINGBASE[jid]['max_date'] = dt
        PINGBASE[jid]['pings'][dt] = sec
        tmp = 0
        for AV in PINGBASE[jid]['pings']:
                tmp+= PINGBASE[jid]['pings'][AV]
        PINGBASE[jid]['average'] = tmp / len( PINGBASE[jid]['pings'] )



def handler_ping_answ(coze, res, t0, mtype, source, param):
	id = res.getID()
	inf = ''
	if id in globals()['ping_pending']:
		globals()['ping_pending'].remove(id)
	else:
		print 'someone is doing wrong...'
		return
	if res:
		if res.getType() == 'result':
			t = time.time()
			rep = u''
			second = round(t-t0, 3)
			if param:
				rep +=random.choice([u'pong from '+param+u' is', u'Response rate for the server '+param+u' is', u'The rate of sending packets from '+param+u' is', u'aha! What I dug up! This is Pong on '+param+':'])   
			else:
				rep += random.choice([u'Your pong is', u'Response rate is equal to the server for you', u'The rate of sending your ping', u'aha! What I dug up! This is your pong:'])
			rep+=u' '+str(second)+u' seconds'
			png = second
			handler_ping_log( get_true_jid(source[0]), second )
			if png < 0.10:
				if not param:
					inf = u'your net is really reactive!'
				else:
					inf = u'its a reactive net!'
			if  (png >= 0.10) & (png < 0.50):
				if not param:
					inf = u'you have a great pong!'
				else:
					inf = u'its a great pong!'
			if (png >= 0.50) & (png < 1.00):
				if not param:
					inf = u'a normal pong! GPRS, yes?!'
				else:
					inf = u'its very normal! GPRS?'
			if (png >= 1.00) & (png < 1.20):
				if not param:
					inf = u'your pong is normal, GPRS'
				else:
					inf = u'his is normal, GPRS'
			if (png >= 1.20) & (png < 1.60):
				if not param:
					inf = u'your net is slow, GPRS'
				else:
					inf = u'its a slow pong, GPRS'
			if (png >= 1.60) & (png < 2.00):
				if not param:
					inf = u'Your pong is very slow, GPRS'
				else:
					inf = u'his pong sucks, GPRS'
			if (png >= 2.00) & (png < 6.00):
				if not param:
					inf = u'you broke your pong, GPRS'
				else:
					inf = u'his pong broken, GPRS'
			if (png >= 6.00):
				if not param:
					inf = u'its up the wall'
				else:
					inf = u'its dead'
			rep = rep + ' - ' + inf
		else:
			rep = u'not pinging'
	reply(mtype, source, rep)

def handler_ping_stats(type, source, parameters):
        if parameters:
                if parameters in GROUPCHATS[source[1]].keys():
                        JID = GROUPCHATS[source[1]][parameters]['jid']
                else:
                        reply(type, source, u'hmmm?')
                        return
        else:
                JID = get_true_jid(source[0])
        if PINGBASE.has_key(JID):
                TEXT = u'Statistics has %s ping \nshortest ping %s was recorded [%s] \nlongest ping %s was recorded [%s] \naverage length of ping: %s' % (str(len(PINGBASE[JID]['pings'])), str(PINGBASE[JID]['min']), str(PINGBASE[JID]['min_date']), str(PINGBASE[JID]['max']), str(PINGBASE[JID]['max_date']), str(round(PINGBASE[JID]['average'], 3)) )
        else:
                TEXT = u'you have not pinged so ask statistics ]:->'
        reply(type, source, TEXT)


        

register_command_handler(handler_ping_stats, 'pingstat', ['info','muc','all'], 0, 'displays ping statistics.', 'pingstat [nick]', ['pingstat guy','pingstat jabber.aq'])
	
register_command_handler(handler_ping, '.', ['info','muc','all'], 10, 'Pings you, or a specific server or nickname.', '. [nick]', ['. guy','. jabber.aq'])
